/****************************************************************************
  From Qt examples
****************************************************************************/

#include "serverthread.h"

#include <QtNetwork>
#include <iostream>
using namespace std;

ServerThread::ServerThread(int socketDescriptor, const QString &message, QObject *parent)
    : QThread(parent), socketDescriptor(socketDescriptor), text(message)
{
    this->socketDescriptor = socketDescriptor;
}

void ServerThread::run()
{
    //Thread starts here
    blockS=0;
    //qDebug()<< socketDescriptor << "Starting Thread";
    socket = new QTcpSocket();
    if (!socket->setSocketDescriptor(this->socketDescriptor)) {
        emit error(socket->error());
        return;
    }
    //direct connection to the thread
    connect(socket,SIGNAL(readyRead()),this,SLOT(readyRead()),Qt::DirectConnection);
    connect(socket,SIGNAL(disconnected()),this,SLOT(disconnect()),Qt::DirectConnection);

    //qDebug()<< socketDescriptor << "Client Connected";

    //test
    exec();

}

void ServerThread::readyRead()
{
   // blockS=0;
   // QByteArray Data = socket->readAll();
  //  QString myString(Data);
  //  QString temp = Data;

    //qDebug() << "Original blockSize: " << blockS;

    QDataStream in(socket);
    in.setVersion(QDataStream::Qt_4_0);

    if (blockS == 0) {
        if (socket->bytesAvailable() < (int)sizeof(quint16))
            return;
        in >> blockS;
    }

    //qDebug() << "BlockSize: " << blockS;

    if (socket->bytesAvailable() < blockS)
        return;

    //qDebug() << "Recieved the full msg";

    QString nextMessage;
    in >> nextMessage;
    text = nextMessage;

    //qDebug() << socketDescriptor << "Message in: " << nextMessage;

    blockS = 0;

    emit clientMessage(nextMessage);
    //socket->write(Data);
    //qDebug() << "Server Write back";
}


// This function can be used to communicate with all the connected clients
// Echoes the given message to all clients connected
void ServerThread::sendServerInformation(QString info)
{
    //qDebug() << "Server Thread is sending server information to the proxy: " << info;

    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);
    out << (quint16)0;
    out << info;
    out.device()->seek(0);
    out << (quint16)(block.size() - sizeof(quint16));

    socket->write(block);

    //qDebug() << "Server Thread wrote: " << info;

}

void ServerThread::disconnect()
{
    //qDebug() << socketDescriptor << "Disconnecting: ";

    socket->deleteLater();
    exit(0); // Thread no longer needed
}


